package com.ljw.gulimall.order.web;


import com.ljw.gulimall.order.entity.OrderEntity;
import com.ljw.gulimall.order.service.OrderService;
import com.ljw.gulimall.order.vo.OrderConfirmVo;
import com.ljw.gulimall.order.vo.OrderSubmitVo;
import com.ljw.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.UUID;

@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @ResponseBody
    @GetMapping("/testtestRabbitMQ")
    public String testRabbitMQ(){
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(UUID.randomUUID().toString());
        orderEntity.setModifyTime(new Date());
        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderEntity);
        return "ok";
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", orderConfirmVo);
        return "confirm";
    }

    /**
     * 提交订单
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model){
        //去创建订单，验令牌，验价格，所库存......
        SubmitOrderResponseVo responseVo =  orderService.submitOrder(orderSubmitVo);
        //下单成功来到支付选择页
        //下单失败回到订单确认页重新确认订单信息
        if (responseVo.getCode() == 0){
            //下单成功来到支付页选择页
            model.addAttribute("submitOrderResponseVo", responseVo);
            return "pay";
        }else {
            return "redirect:http://order.gulimall.com/toTarde";
        }
    }

}
